import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserService } from '../user/user.service';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private userService: UserService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredLevel = this.reflector.get<number>('level', context.getHandler());
    if (!requiredLevel) {
      return true;
    }

    const { user } = context.switchToHttp().getRequest();
    if (!user) {
      return false;
    }

    // 级别1是最高管理者，可以访问所有内容
    if (user.level === 1) {
      return true;
    }

    // 如果需要的级别比用户级别低（数字大），则允许访问
    if (requiredLevel > user.level) {
      return true;
    }

    // 对于特定资源的访问控制（如查看下级的项目）
    const resourceId = context.switchToHttp().getRequest().params.id;
    if (resourceId) {
      const subordinates = await this.userService.getSubordinates(user.userId);
      const resourceOwnerId = context.switchToHttp().getRequest().resourceOwnerId;
      
      if (resourceOwnerId && 
          (resourceOwnerId === user.userId || 
           subordinates.some(sub => sub.id === resourceOwnerId))) {
        return true;
      }
    }

    return false;
  }
}